package com.demo.camunda.controller;

import com.alibaba.fastjson.JSONObject;
import com.demo.camunda.entity.User;
import com.demo.camunda.service.TempService;
import com.demo.camunda.service.UserService;
import com.demo.camunda.util.CommonResult;
import com.demo.camunda.util.JWTUtil.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/UserController")
public class UserController {

    @Resource
    private TempService tempService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    //登录
    @PostMapping("/login")
    public Object login(@RequestBody @Validated User user){
        JSONObject jsonObject=new JSONObject();
        User userForBase=userService.findUserById(user.getId());
        if(userForBase==null){
            jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;
        }else {
            if (!userForBase.getUserPassWord().equals(user.getUserPassWord())){
                jsonObject.put("message","登录失败,密码错误");
                return jsonObject;
            }else {
                String token = jwtTokenUtil.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }

    @PostMapping("/addUser")
    public CommonResult addUser(@RequestBody User user){
        //对密码进行加密
        user.setUserPassWord(bCryptPasswordEncoder.encode(user.getUserPassWord()));
        userService.addUser(user);
        return CommonResult.success();
    }

    @GetMapping("/findAll")
    //@PreAuthorize("hasAnyAuthority('ADMIN')")  //这一步很重要 拥有ADMIN权限的用户才能访问该请求
    public List<User> findAll(){
        return userService.findAllUser();
    }

//    @UserLoginToken
//    @GetMapping("/getMessage")
//    public String getMessage(){
//        return "你已通过验证";
//    }
}
